<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button
          v-if="meta.indexOf('SpecialCaradOrderListExport') > -1"
          :loading="exportLoading"
          type="primary"
          @click="handleExport"
        >{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tableb"
    >
      <el-table-column
        align="center"
        :label="$t('message.ddh')"
        min-width="220"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.orderId)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in propList"
        :key="item.label"
        align="center"
        :label="item.label"
        :min-width="item.minWidth"
        show-overflow-tooltip
        :prop="item.prop"
      />
      <el-table-column
        align="center"
        :label="$t('message.status')"
        min-width="100"
        prop="payStatusName"
        fixed="right"
      />
      <el-table-column
        align="center"
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH'? 160 : 230"
        fixed="right"
      >
        <template slot-scope="scope">
          <div
            class="flex-cc"
          >
            <el-button
              v-if="scope.row.payStatus == '0' && meta.indexOf('SpecialCardOrderContinuePay') > -1"
              v-preventReClick
              type="text"
              @click="handlePay(scope.row)"
            >{{ $t('message.zf') }}</el-button>
            <el-button
              v-if="scope.row.payStatus == '0' && meta.indexOf('SpecialCardOrderCancelPay') > -1"
              v-preventReClick
              type="text"
              @click="handleCancel(scope.row)"
            >{{ $t('message.qxzf') }}</el-button>
            <el-button
              v-if="scope.row.payStatus == '3'"
              v-preventReClick
              type="text"
              @click="printTC(scope.row.orderId)"
            >{{ $t('message.dyxp') }}</el-button>
            <el-button
              v-if="scope.row.payStatus == '3' && meta.indexOf('SpecialCardOrderRefund') > -1"
              v-preventReClick
              type="text"
              @click="handleRefund(scope.row)"
            >{{ $t('message.tk') }}</el-button>
          </div>
          <div v-if="scope.row.payStatus != '0' && scope.row.payStatus != '3'" class="flex-cc">-</div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @SizeChange="pageSizeChange"
      @current-change="getList"
    />

    <el-dialog
      :title="$t('message.ddtk')"
      :visible.sync="isShowRefund"
      width="600px"
    >
      <div class="fs_12">{{ $t('message.ddtksm') }}</div>
      <div class="fs_12 refund_header mt10 mb20">
        <div>{{ $t('message.sfje') }}：</div>
        <div class="red fs_18 mt10">{{ refundForm.realPrice }}</div>
      </div>
      <el-form
        ref="refundRef"
        :model="refundForm"
        :rules="rules"
        label-width="auto"
        label-suffix="："
      >
        <el-form-item :label="$t('message.tkje')" prop="refundPrice">
          <el-input
            v-model="refundForm.refundPrice"
            oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            class="w200 mr10"
          />
          <span>{{ $t('message.yuan') }}</span>
          <div class="placeholder9">{{ $t('message.zgktjewsfje') }}</div>
        </el-form-item>
        <el-form-item :label="$t('message.tkyy')" prop="remark">
          <el-input v-model="refundForm.remark" :placeholder="$t('message.qsr') + $t('message.tkyy')" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowRefund = false">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="subRefund">{{ $t('message.tk') }}</el-button>
      </span>
    </el-dialog>
    <orderDialog v-if="isShowOrder" ref="orderRef" @orderSuccess="getList" />
    <orderDetail ref="orderDetail" />
    <RechargeTem v-if="isPrint" ref="RechargeTemRef" />
  </div>
</template>

<script>
import {
  specialCardOrder,
  specialCardOrderEx,
  specialCardOrderCancel,
  specialCardOrderPay,
  specialCardOrderRefund,
  getOrderTypeQuery,
  printOrder
} from '@/api'
// import { parseTime } from '@/utils'
import orderDialog from '@/components/order'
import Paginations from '@/components/paginations/paginations'
import QueryForm from '@/components/QueryForm'
import orderDetail from './detail.vue'
import RechargeTem from '@/components/printTem/recharge.vue'
import { TJshortcuts } from '@/utils/config'
export default {
  name: 'TicketOrder',
  components: {
    orderDialog,
    QueryForm,
    orderDetail,
    Paginations,
    RechargeTem
  },
  data() {
    return {
      exportLoading: false,
      isShowOrder: false,
      isPrint: false,
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: this.$t('message.ddh')
        }, {
          filed: 'memberInfo',
          type: 'input',
          label: this.$t('message.memberInfo'),
          placeholder: this.$t('message.hy2'),
          clearable: true
        }, {
          filed: 'selTime',
          label: this.$t('message.createTime'),
          type: 'daterange',
          clearable: true,
          pickerOptions: {
            shortcuts: TJshortcuts
          }
        }, {
          filed: 'specialCardName',
          type: 'input',
          label: this.$t('message.zxk')
        }, {
          filed: 'payStatus',
          type: 'select',
          label: this.$t('message.ddzt'),
          placeholder: this.$t('message.qxz') + this.$t('message.ddzt'),
          clearable: true,
          labelCode: 'name',
          options: []
        },
        {
          filed: 'createName',
          type: 'input',
          label: this.$t('message.czr'),
          clearable: true
        }],
        online: true
      },
      isShowRefund: false,
      refundForm: {},
      rules: {
        remark: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }],
        refundPrice: [{ required: true, message: this.$t('message.qsr'), trigger: 'blur' }]
      },
      propList: [
        { label: this.$t('message.memberInfo'), prop: 'memberInfo', minWidth: 220 },
        { label: this.$t('message.zxk'), prop: 'specialCardInfo', minWidth: 160 },
        { label: this.$t('message.num'), prop: 'specialCardNum', minWidth: 60 },
        { label: this.$t('message.ddhjy'), prop: 'price', minWidth: 110 },
        { label: this.$t('message.jyfs'), prop: 'pathMethodName', minWidth: 110 },
        { label: this.$t('message.jyqd'), prop: 'channel', minWidth: 120 },
        { label: this.$t('message.createTime'), prop: 'createTime', minWidth: 160 }
      ],
      meta: [],
      list: [],
      total: 0,
      pagination: {
        page: 1,
        rows: 10
      },
      listLoading: false,

      filters: {
        selTime: []
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    // this.getInitData()
    this.getOrderStatusList()
    this.getList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
      }
      if (filters.selTime) {
        filters.startTime = filters.selTime[0]
        filters.endTime = filters.selTime[1]
      } else {
        filters.startTime = ''
        filters.endTime = ''
      }
      this.listLoading = true
      specialCardOrder({
        pagination, param: {
          ...filters
        }
      }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.total = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    handlePay(row) {
      const { orderId } = row
      specialCardOrderPay({ param: { orderId }}).then(res => {
        this.isShowOrder = true
        this.$nextTick(() => {
          this.$refs.orderRef.continuePay({ ...res.record }, 'specialCardBuy')
        })
      })
    },
    handleCancel(row) {
      const { orderId } = row
      this.$confirm(this.$t('message.qxzftc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      }).then(() => {
        specialCardOrderCancel({ param: { orderId }}).then(res => {
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.qxzfcg'))
          this.getList()
        })
      })
    },
    handleRefund(row) {
      this.isShowRefund = true
      this.refundForm = { ...row, refundPrice: row.realPrice }
    },
    getOrderStatusList() {
      getOrderTypeQuery({ param: {}}).then(res => {
        this.queryFormConfig.formItems[4].options = res.recordList || []
      })
    },
    subRefund() {
      this.$refs['refundRef'].validate((valid) => {
        if (valid) {
          specialCardOrderRefund({ param: { ... this.refundForm }}).then(res => {
            if (res.errorCode !== '000000') return
            this.isShowRefund = false
            this.$message.success(this.$t('message.tktcqr'))
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    pageSizeChange(val) {
      this.pagination.rows = val
      this.getList(1)
    },
    handleExport() {
      const { filters } = this
      if (filters.selTime) {
        filters.startTime = filters.selTime[0]
        filters.endTime = filters.selTime[1]
      } else {
        filters.startTime = ''
        filters.endTime = ''
      }
      this.exportLoading = true
      specialCardOrderEx({
        param: {
          ...filters
        }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            const a = document.createElement('a') // 创建一个a标签元素
            a.style.display = 'none' // 设置元素不可见
            a.href = res.record.showUrl // 设置下载地址
            document.body.appendChild(a) // 加入
            a.click() // 触发点击,下载
            document.body.removeChild(a) //
            this.$message.success(this.$t('message.dccg'))
          }
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
    handleDetail(id) {
      // this.$router.push({ name: 'ticketOrderDetail', query: { id }})
      this.$refs.orderDetail.getDetail(id)
    },
    clear() {
      this.filters = {
        selTime: []
      }
      this.getList(1)
    },
    printTC(id) {
      this.isPrint = true
      printOrder({
        param: {
          contentMap: {},
          venueId: sessionStorage.getItem('venueId'),
          workId: id,
          templateCode: 'SPECIAL_CARD_ORDER'
        }
      })
        .then(res => {
          if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
            res.record.dataList.forEach(item => {
              this.$refs.RechargeTemRef.obj = { ...item }
              this.$refs.RechargeTemRef.desc = this.$t('message.dytsy1')
              setTimeout(() => {
                this.$refs.RechargeTemRef.print()
              }, 300)
              setTimeout(() => {
                this.isPrint = false
              }, 500)
            })
          } else {
            this.isPrint = false
          }
        })
        .catch(() => {
          this.isPrint = false
        })
    }
  }
}
</script>

<style lang='scss' scoped>
.refund_header{
  background-color: #f5f7fc;
  padding: 12px;
}
</style>
